'''
Created on 9 nov. 2012

@author: jurgen_reintjes
'''
from contourDetectionCanny import contourDetectionCanny
from contourDetectionSoble import contourDetectionSoble
from differencesDetector import differencesDetector
from perspectiveTransform import perspectiveTransform 
from Client import Client
import cv2

CORNERS = (6,9)

class Vision():
    def __init__(self, goodimage, debug):
        self.debug = debug
        self.width = -1
        self.height = -1
        self.goodimage = goodimage
        self.pT = None
        self.client = None
        self.running = False
        self.cDC = None
        self.calibrated = False

    def start(self, algorithme, ip, port):
            
        self.cap = cv2.VideoCapture(0)
        self.client = Client(self, ip, port)
        self.client.connect()
        
        if not self.client.socket_available:
            self.width = 800
            self.height = 600
            
        while self.width == -1 or self.height == -1:
            cv2.waitKey(10)
        
        if algorithme is "soble":
            self.cDC = contourDetectionSoble(debug=self.debug)
        elif algorithme is "canny":
            self.cDC = contourDetectionCanny(debug=self.debug)
        elif algorithme is "Detector":
            self.cDC = differencesDetector(self.goodimage,debug=self.debug)
        
    def getFrame(self):
        s, img = self.cap.read()
        if self.calibrated:
            img = self.rectifie(img)
        else:#work around otherwise deadlock
            cv2.waitKey(10)
            cv2.imshow("frame", img)
        cv2.waitKey(1)
        return img
    
    def setResolution(self, width, height):
        self.width = width
        self.height = height
    
    def calibrate(self):
        if self.width > 0 and self.height > 0:
            if self.pT == None:
                self.pT = perspectiveTransform(self.width,self.height,debug=self.debug)            
            self.calibrated = self.pT.calibration(cv2.imread("C:\\calib.png"),self.getFrame(),CORNERS)
            if self.calibrated:
                self.running =True
            return self.calibrated
        else:
            raise Exception("width or height is null")
    
    def rectifie(self, frame):
        return self.pT.rectifie_frame(frame)
    
    def run(self):
        frame = self.getFrame()
        data  = self.cDC.proces(frame)
        if(self.debug):
            self.cDC.show(data)

        self.client.send(self.cDC.getJsonString(data)+"\n")
                
    def stop(self):
        self.running = False
        self.client.disconnect()